package net.atomarrow.plugins;

import java.util.ArrayList;
import java.util.List;

import net.atomarrow.ioc.ActionContext;
import net.atomarrow.ioc.ApplicationContext;
import net.atomarrow.util.PriorityUtil;

/**
 * 插件管理
 * @author Michael
 *
 */
public class PluginManager {

	private List<Plugin> plugins;
	
	public PluginManager(){
		plugins=new ArrayList<Plugin>();
	}
	/**
	 * 加载插件
	 * @param paths
	 */
	public void loadPlugins(List<String> paths) {
        Class clazz;
        try {
        	Plugin plugin;
            for (String path : paths) {
                clazz = Class.forName(path);
                if(Plugin.class.isAssignableFrom(clazz)){
                	plugin = (Plugin) clazz.newInstance();
                	ApplicationContext.load(plugin);
                	plugins.add(plugin);
                }
            }
            this.plugins = PriorityUtil.sort(plugins);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } 
    }
	public void startPlugins() {
		for(Plugin plugin:plugins){
			ActionContext.init(null, null, null,null);
			plugin.start();
			ActionContext.destory();
		}
	}
	public void stopPlugins() {
		for(Plugin plugin:plugins){
			ActionContext.init(null, null, null,null);
			plugin.stop();
			ActionContext.destory();
		}
	}

}
